import multiprocessing
import time
from multiprocessing.managers import BaseManager

import location_conn
import location_design
from simulate_engine import simulate_map
from simulate_engine import engine_conn

if __name__ == '__main__':
    loc_manager = BaseManager()
    loc_manager.register('location_server',location_conn.LocationServer)
    loc_manager.start()

    server_init = multiprocessing.Value('i', 0)

    sim_manager = BaseManager()
    sim_manager.register('simulate_map',simulate_map.SimulateMap)
    sim_manager.start()

    dsp_manager = BaseManager()
    dsp_manager.register('resource_manager',location_design.DispalyResourceManager)
    dsp_manager.start()

    loc_server = loc_manager.location_server()
    simulate_map = sim_manager.simulate_map()
    loc_server.bind_simulte_map(simulate_map)
    
    res_manager = dsp_manager.resource_manager()
    res_manager.register_location_server(loc_server)
    
    process_name = 'raise_location_server'
    proc_server = multiprocessing.Process(
        target=location_conn.raise_location_server,
        args=(process_name,loc_server)
    )
    proc_server.daemon = True

    process_name = 'raise_display'
    proc_display = multiprocessing.Process(
        target=location_design.raise_loction_display,
        args=(process_name,simulate_map,res_manager,server_init)
    )


    process_name = 'raise_simulate_engine'
    proc_sim_engine = multiprocessing.Process(
        target=engine_conn.raise_simulate_engine,
        args=(process_name,loc_server,simulate_map)
    )

    proc_server.start()
    proc_display.start()
    proc_sim_engine.start()

    proc_server.join()
    print("join end!!!")
    print(server_init.value)
    while server_init.value == 1:
        server_init.value=0
        print("+value = ",server_init.value)
        loc_server = loc_manager.location_server()
        process_name = 'raise_location_server'
        proc_server = multiprocessing.Process(
            target=location_conn.raise_location_server,
            args=(process_name,loc_server)
        )
        proc_server.daemon = True
        proc_server.start()
        res_manager.register_location_server(loc_server)
        proc_server.join()
        print("-- join end")

    proc_display.terminate()
    proc_sim_engine.terminate()

